package com.examsystem.filter;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.examsystem.util.JwtUtil;
import com.examsystem.pojo.vo.LoginUser;
import com.examsystem.pojo.vo.Result;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author fire'ge
 */
@Component
public class JwtFilter extends OncePerRequestFilter  {
    @Resource
    RedisTemplate<Object,Object> template;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = httpServletRequest.getHeader("token");
        if(httpServletRequest.getHeader("sec-websocket-protocol")!=null){
            token = httpServletRequest.getHeader("sec-websocket-protocol");
        }
        if (token==null){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        //验证token
        try{
             int jwtUserId = JwtUtil.getJWTUserId(token);
            LoginUser loginUser = (LoginUser) template.opsForValue().get("login:user"+jwtUserId);
            if (loginUser==null){
                httpServletResponse.setContentType("application/json;charset:utf-8");
                httpServletResponse.getWriter().println(JSON.toJSONString(Result.fail("noLogin")));
                return;
            }
            //放入SecurityContextHolder
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());

            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            filterChain.doFilter(httpServletRequest,httpServletResponse);

        }catch (TokenExpiredException e){
            httpServletResponse.setContentType("application/json;charset=utf-8");
            httpServletResponse.getWriter().println(JSON.toJSONString(Result.fail(e.getMessage())));
        }

    }
}
